package com.edais.service.imp;

import com.edais.dao.*;
import com.edais.domain.ActivitySendMessage;
import com.edais.domain.ConfigSms;
import com.edais.domain.WithdrawErrorSendMobile;
import com.edais.service.SMSService;
import com.edais.util.*;
import com.edais.util.RSAThirdParty.RSA;
import com.edais.util.weixinAbout.HttpRequestParam;
import com.edais.util.zsht.ZSHTPayThridPartyFunctionUtil;
import com.umpay.api.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class SMSServiceImp implements SMSService {

	private static final Log logger = LogFactory.getLog(SMSServiceImp.class);

	@Autowired
	private CaptchaDao captchaDao;

	@Autowired
	private ActivitySendMessageDao activitySendMessageDao;

	@Autowired
	private ConfigSmsDao configSmsDao;

	@Autowired
	private RateRisesCouponsDao rateRisesCouponsDao;

	@Autowired
	private UserDao usersDao;

	@Autowired
	private UserCardDao userCardDao;

	@SuppressWarnings("unchecked")
	@Override
	public String getJxCouponRate(String key) throws Exception {
		List<String> listStr = new ArrayList<String>();
		listStr.add(key);
		// 去BL查询系统参数表
		List<Map<String, Object>> extractFeeRate = rateRisesCouponsDao.queryParamName(listStr);
		if (extractFeeRate != null && extractFeeRate.size() > 0) {
			return (String) extractFeeRate.get(0).get("VALUE");
		}
		return null;
	}

	/**
	 * 保存短信到DB
	 */
	@Override
	public void saveSMS(String mobileNum, String message, String flag) throws Exception {
		ActivitySendMessage newMessageInfo = new ActivitySendMessage();
		newMessageInfo.setMessage_text(message);
		newMessageInfo.setSetup_flag(flag);
		newMessageInfo.setSetup_result(1);
		newMessageInfo.setMobile_number(mobileNum);
		this.activitySendMessageDao.addActivitySendMessage(newMessageInfo);
	}

	/**
	 * 根据用户id获取用户手机号
	 */
	@Override
	public String getMobileById(String userId) throws Exception {
		return this.captchaDao.getMobileById(userId);
	}

	@Async
	@Override
	public Map<String, Object> sendSMS(String logInfo, String mobile, String smsNo, String... smsParams)
			throws Exception {
		Map<String, Object> retMap = new HashMap<String, Object>();
		
		ConfigSms ss = configSmsDao.selectByPrimaryKey(smsNo);
		String smsContext = ss.getSmsContext();
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < smsParams.length; i++) {
			map.put(String.valueOf(i), smsParams[i]);
		}
		String content = "【糯糯金融】" + tSmsContent(smsContext, map);
		String sendSmsChannel = ss.getSmsChannel();
		if (sendSmsChannel != null && "0".equals(sendSmsChannel.trim())) {
			// Channel=0 表示短信关闭
			logger.info(logInfo + "发送短信渠道：关闭");
			return null;
		}
		logger.info(logInfo + "发送短信渠道：" + sendSmsChannel);
		Map<String, String> semParams = new HashMap<String, String>();
		semParams.put("content", content);
		semParams.put("send_sms_channel", sendSmsChannel);
		semParams.put("mobileListParams", mobile);
		ZSHTPayThridPartyFunctionUtil.sendErrorMessage(semParams);
		// 保存验证码到DB
		try {
			this.saveSMS(mobile, content, sendSmsChannel);// send_sms_channel// 1-短信宝 2-月呈
		} catch (Exception e) {
			logger.error("/sendSMS/getSMS  短信保存失败，失败原因：" + e.getCause());
		}
		
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg_cn", "发送成功");
		return retMap;
	}

	public Map<String, Object> sendSystemSMS(String logInfo, String smsNo, String... smsParams) throws Exception {
		return null;
	}

	@Override
	public Map<String, Object> getSMS(String userId, String methodName, String je) throws Exception {
		return pjMap(userId, methodName, je, "");
	}

	@Override
	public Map<String, Object> getSMS(String userId, String smsNo, String je, String cpType) throws Exception {
		return pjMap(userId, smsNo, je, cpType);
	}

	@Override
	public Map<String, Object> getSMSKz(String userId, String methodName) throws Exception {
		return pjMapKz(userId, methodName, "", "");
	}

	@Override
	public Map<String, Object> getSMSKz(String userId, String methodName, String parm1) throws Exception {
		return pjMapKz(userId, methodName, parm1, "");
	}

	@Override
	public Map<String, Object> getSMSKz(String userId, String methodName, String parm1, String parm2) throws Exception {
		return pjMapKz(userId, methodName, parm1, parm2);
	}

//	@Async
	@Override
	public Map<String, Object> setSMS(String mobile, String context) throws Exception {

		Map<String, Object> rtnMap = new HashMap<String, Object>();
		if (StringUtil.isEmpty(mobile)) {
			logger.debug("/sendSMS/setSMS " + Message.CnDescriptionExpression.MOBILE_IS_NONBOUND + "手机号：" + mobile);
			return rtnMap;
		}

		// 校验手机号是否合法
		if (!mobile.matches(Consts.PHONECHECK)) {
			logger.debug("/sendSMS/setSMS 用户已绑定手机格式不对！手机号：" + mobile);
			return rtnMap;
		}
		// (手机)短信系统 工具
		logger.debug("手机号：" + mobile + "内容：" + context);

		// 获取短信模版
		String conent = "【糯糯金融】" + context;
		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("content", conent);
		// paramMap.put("mobileListParams", mobile);
		paramMap.put("mobileListParams", mobile);
		// String param = CommonUtil.getHttpParameterFromMap(paramMap);
		// 增加多个短信渠道
		String send_sms_channel = "";
		try {
			send_sms_channel = getJxCouponRate("send_sms_channel");
			logger.debug("send_sms_channel==" + send_sms_channel);
		} catch (Exception e1) {
			e1.printStackTrace();
			logger.error("获取短信渠道参数出错：" + e1);
		}
		paramMap.put("send_sms_channel", send_sms_channel);
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串：" + e);
		}

		// 发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(smsResult)) {
			// 失败
			logger.debug("/sendSMS/setSMS " + mobile + "发送失败！手机号：" + mobile);
			return rtnMap;
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if (null == smsResultMap || "sysException".equals(smsResultMap.get("rescode"))) {
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				// 失败
				return rtnMap;
			} else if ("BusinessException".equals(smsResultMap.get("rescode"))) {
				// 业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				return rtnMap;
			}
		}

		// 保存验证码到DB
		try {
			this.saveSMS(mobile, conent, send_sms_channel);// send_sms_channel
															// 1-短信宝 2-月呈
		} catch (Exception e) {
			logger.error("/sendSMS/getSMS  短信保存失败，失败原因：" + e.getCause());
		}

		rtnMap.put("mobile", mobile);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
		rtnMap.put("resmsg_cn", "");

		return rtnMap;
	}

	private Map<String, Object> pjMap(String userId, String smsNo, String je, String cpType) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		// String mobile ="18058737296";
		String mobile = this.captchaDao.getMobileById(userId);
		if (StringUtil.isEmpty(mobile)) {
			mobile = userId;
		}
		if (StringUtil.isEmpty(mobile)) {
			logger.debug("/sendSMS/getSMS " + Message.CnDescriptionExpression.MOBILE_IS_NONBOUND + "手机号：" + mobile);
			return rtnMap;
		}

		// 校验手机号是否合法
		if (!mobile.matches(Consts.PHONECHECK)) {
			logger.debug("/sendSMS/getSMS 用户已绑定手机格式不对！手机号：" + mobile);
			return rtnMap;
		}
		ConfigSms ss = configSmsDao.selectByPrimaryKey(smsNo);
		String sendSmsChannel = ss.getSmsChannel();
		if (sendSmsChannel != null && "0".equals(sendSmsChannel.trim())) {
			// Channel=0 表示短信关闭
			logger.info("发送短信渠道：关闭");
			return rtnMap;
		}
		if (ss == null || StringUtils.isBlank(ss.getSmsContext())) {
			logger.debug("/sendSMS/getSMS 短信不匹配!");
			return rtnMap;
		}
		// (手机)短信系统 工具
		logger.debug("手机号：" + mobile + "金额：" + je + "短信类型：" + smsNo + "产品名称：" + cpType);

		// (手机)短信系统 工具
		// SanTongSmsUtil smsUtil = new SanTongSmsUtil();
		// 发送短信
		Map<String, String> map = new HashMap<String, String>();
		// 修改所有涉及发短信金额保留两位小数 by ouyy
		if ("sms01001".equals(smsNo) || "sms02001".equals(smsNo) || "sms02002".equals(smsNo) || "sms03001".equals(smsNo)
				|| "sms04001".equals(smsNo) || "sms05001".equals(smsNo) || "sms08001".equals(smsNo) || "sms02003".equals(smsNo)) {
			try {
				map.put("0", CommonUtil.setFormatMoney(je));
			} catch (Exception e) {
				e.printStackTrace();
				map.put("0", je);
			}
		} else {
			map.put("0", je);
		}
		map.put("1", cpType);
		//
		Map reMap = configSmsDao.selectRealName(mobile);
		String realName = "";
		if (reMap == null || reMap.size() == 0) {
			realName = "手机尾号" + mobile.substring(mobile.length() - 4);
		} else {
			realName = (String) reMap.get("REAL_NAME") == null ? "" : (String) reMap.get("REAL_NAME");
		}
		map.put("2", realName);
		// 获取短信模版
		String conent = "【糯糯金融】" + tSmsContent(ss.getSmsContext(), map);
		
		//在发送短信之前发送个推消息----add by gongyanlan
//		 if("1".equals(ss.getSmsEx1())){
//			Map<String,Object> paramMap2=new HashMap<String,Object>();
//			if("sms01001".equals(smsNo)
//					 ||"sms02001".equals(smsNo)
//					 ||"sms03001".equals(smsNo)
//					 ||"sms04001".equals(smsNo)
//					 ||"sms05001".equals(smsNo)
//					 ||"sms08001".equals(smsNo)){
//				paramMap2.put("title", "回款通知");//标题
//				paramMap2.put("messageDetailTypeNew", "2");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
//			}else if("sms01001".equals(smsNo)){
//				paramMap2.put("title", "充值成功通知");
//				paramMap2.put("messageDetailTypeNew", "3");
//			}else if("sms01001".equals(smsNo)){	
//				paramMap2.put("title", "投资通知");
//				paramMap2.put("messageDetailTypeNew", "4");
//			}else if("sms01001".equals(smsNo)){	
//				paramMap2.put("title", "提现成功通知");
//				paramMap2.put("messageDetailTypeNew", "5");
//			}
//			paramMap2.put("userId", userId);
//			paramMap2.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
//			paramMap2.put("content", conent);//消息模板里需要替换的变量
//			this.sendGetuiMSG(paramMap2);
//	 }
		
		
		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("content", conent);
		// paramMap.put("mobileListParams", mobile);
		paramMap.put("mobileListParams", mobile);
		// String param = CommonUtil.getHttpParameterFromMap(paramMap);

		paramMap.put("send_sms_channel", sendSmsChannel);
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串：" + e);
		}

		// 发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(smsResult)) {
			// 失败
			logger.debug("/sendSMS/getSMS " + smsNo + "发送失败！手机号：" + mobile);
			return rtnMap;
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if (null == smsResultMap || "sysException".equals(smsResultMap.get("rescode"))) {
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				// 失败
				return rtnMap;
			} else if ("BusinessException".equals(smsResultMap.get("rescode"))) {
				// 业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				return rtnMap;
			}
		}

		// 保存验证码到DB
		try {
			this.saveSMS(mobile, conent, sendSmsChannel);// send_sms_channel
															// 1-短信宝 2-月呈
		} catch (Exception e) {
			logger.error("/sendSMS/getSMS  短信保存失败，失败原因：" + e.getCause());
		}

		rtnMap.put("mobile", mobile);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
		rtnMap.put("resmsg_cn", "");

		return rtnMap;
	}

	private Map<String, Object> pjMapKz(String userId, String smsNo, String parm1, String parm2) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		String mobile = this.captchaDao.getMobileById(userId);
		if (StringUtil.isEmpty(mobile)) {
			mobile = userId;
		}
		if (StringUtil.isEmpty(mobile)) {
			logger.debug("/sendSMS/getSMS " + Message.CnDescriptionExpression.MOBILE_IS_NONBOUND + "手机号：" + mobile);
			return rtnMap;
		}

		// 校验手机号是否合法
		if (!mobile.matches(Consts.PHONECHECK)) {
			logger.debug("/sendSMS/getSMS 用户已绑定手机格式不对！手机号：" + mobile);
			return rtnMap;
		}
		ConfigSms ss = configSmsDao.selectByPrimaryKey(smsNo);
		if (ss == null || StringUtils.isBlank(ss.getSmsContext())) {
			logger.debug("/sendSMS/getSMS 短信不匹配!");
			return rtnMap;
		}
		// (手机)短信系统 工具
		logger.debug("手机号：" + mobile + "参数1：" + parm1 + "短信类型：" + smsNo + "参数2：" + parm2);

		// (手机)短信系统 工具
		// SanTongSmsUtil smsUtil = new SanTongSmsUtil();
		// 发送短信
		Map<String, String> map = new HashMap<String, String>();
		map.put("0", parm1);
		map.put("1", parm2);

		// 获取短信模版
		String conent = tSmsContent(ss.getSmsContext(), map);
		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("content", conent);
		// paramMap.put("mobileListParams", mobile);
		paramMap.put("mobileListParams", mobile);
		// String param = CommonUtil.getHttpParameterFromMap(paramMap);

		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串：" + e);
		}

		// 发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(smsResult)) {
			// 失败
			logger.debug("/sendSMS/getSMS " + smsNo + "发送失败！手机号：" + mobile);
			return rtnMap;
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if (null == smsResultMap || "sysException".equals(smsResultMap.get("rescode"))) {
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				// 失败
				return rtnMap;
			} else if ("BusinessException".equals(smsResultMap.get("rescode"))) {
				// 业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				return rtnMap;
			}
		}

		// 保存验证码到DB
		try {
			this.saveSMS(mobile, conent, "weixin");
		} catch (Exception e) {
			logger.error("/sendSMS/getSMS  短信保存失败，失败原因：" + e.getCause());
		}

		rtnMap.put("mobile", mobile);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg", Consts.SUCCESS_DESCRIBE);
		rtnMap.put("resmsg_cn", "");

		return rtnMap;
	}

	/**
	 * 设置短信模板中的值
	 * 
	 * @param smsNo
	 * @param paraMap
	 * @return
	 */
	public String tSmsContent(String smsContext, Map<String, String> paraMap) {
		try {
			String m = smsContext;
			for (int i = 0; i < paraMap.size(); i++) {
				m = m.replace("{" + i + "}", (CharSequence) paraMap.get(String.valueOf(i)));
			}
			return m;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";

	}

	/**
	 * 发送验证码主处理
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public String getCaptcha(Map<String, String> map) throws Exception {

		// 查询短信发送记录表
		Map<String, Object> querMap = new HashMap<String, Object>();
		querMap.put("userMobile", map.get("userMobile"));
		querMap.put("setupFlag", map.get("setupFlag"));
		Map sendMesRecMap = usersDao.querySendMesRec(querMap);
		String type = map.get("type");
		String conent = "";

		// 防止重复发送
		if (null != sendMesRecMap) {
			Date codeTime = (Date) sendMesRecMap.get("END_SETUP_TIME");
			Date codeTime_10;
			if ("REGISTER".equals(type)) {
				// 注册90秒有效
				codeTime_10 = new Date(codeTime.getTime() + 90 * 1 * 1000);// 1.5分钟后的时间
			} else {
				// 除了注册外其余都是60秒
				codeTime_10 = new Date(codeTime.getTime() + 60 * 1 * 1000);// 1分钟后的时间
			}

			Date now = usersDao.querySysDate();
			if (now.getTime() <= codeTime_10.getTime()) {
				// 不可重复发送
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "",
						Message.CnDescriptionExpression.SMS_BUSY);
				return result;
			}
		}

		// 获取随机验证码:随机产生的6位数字
		// String randomCode = CommonUtil.getRandomCode();
		// ouyy 六位验证码改成四位
		String randomCode = CommonUtil.getRandomCode_Four();
		/*
		 * 验证码类别： 注册验证码(REGISTER), MOBILE_REGISTER:手机注册 登录验证码(WXLOGIN),
		 * 重置登陆密码(FORGET_PASSWORD), FIND_PASSWORD_BY_MOBILE:通过手机找回密码
		 * 解绑手机(MODIFY_MOBILE), MODIFY_BIND_MOBILE:修改绑定手机 绑定手机(BINDING_MOBILE),
		 * MODIFY_BIND_MOBILE:修改绑定手机 MODIFY_PASSWORD:找回登陆密码
		 * MODIFY_PASSWORD:修改注册密码 CASHDRAW:提现
		 */

		// 获取短信模版
		String templateKey = "";
		if ("REGISTER".equals(type)) {
			templateKey = "MOBILE_REGISTER";
		} else if ("FORGET_PASSWORD".equals(type)) {
			templateKey = "FIND_PASSWORD_BY_MOBILE";
		} else if ("MODIFY_MOBILE".equals(type)) {
			templateKey = "MODIFY_BIND_MOBILE";
		} else if ("BINDING_MOBILE".equals(type)) {
			templateKey = "MODIFY_BIND_MOBILE";
		} else if ("MODIFY_PASSWORD".equals(type)) {
			templateKey = "MODIFY_PASSWORD";
		} else if ("CASHDRAW".equals(type)) {
			templateKey = "";
		} else if ("WXLOGIN".equals(type)) {
			templateKey = "sms07001";
		} else {
			templateKey = "";
		}

		Map<String, String> smsMap = new HashMap<String, String>();
		String smsChannel ="";
		if (!templateKey.isEmpty()) {
			// 获取短信模版(数据库)
			ConfigSms ss = configSmsDao.selectByPrimaryKey(templateKey);
			if (ss == null || StringUtils.isBlank(ss.getSmsContext())) {
				logger.debug("/sendSMS/getCaptcha 短信不匹配!");
			} else {
				// 替换参数
				smsMap.put("0", randomCode);
				conent = tSmsContent(ss.getSmsContext(), smsMap);
				smsChannel= ss.getSmsChannel();
			}
		}

		if (conent.isEmpty()) {
			// 获取短信模版(文件)
			smsMap.put("0", randomCode);
			SanTongSmsUtil smsUtil = new SanTongSmsUtil();
			conent = smsUtil.tSmsContent("other_template", smsMap);
		}

		// 发送短信
		querMap.put("randomCode", randomCode);
		usersDao.addSendMsgRec(querMap);

		// 第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("smsUrl");
		// 请求参数封装
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("content", conent);
		paramMap.put("mobileListParams", map.get("userMobile"));
		paramMap.put("send_sms_channel", smsChannel);

		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam = "";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(paramMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串：" + e);
		}

		// 发送短信消息
		String smsResult = CommonUtil.sendPostByHttp(url, requestParam);
		if (StringUtils.isBlank(smsResult)) {
			// 失败
			logger.error("发送短信失败：http请求中断");
			throw new RuntimeException("验证码获取失败！");
		} else {
			// 解析发送结果
			Map smsResultMap = JsonUtil.getMapFromJsonString(smsResult);
			if (null == smsResultMap || "sysException".equals(smsResultMap.get("rescode"))) {
				// 系统异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("验证码获取失败！");
			} else if ("BusinessException".equals(smsResultMap.get("rescode"))) {
				// 业务异常
				logger.error("发送短信失败：" + smsResultMap.get("resmsg_cn"));
				throw new RuntimeException("验证码获取失败！");
			}
		}
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("phoneNum", map.get("userMobile"));

		String result = CommonUtil.setResultStringCn(resMap, Consts.SUCCESS_CODE, "", "短信发送成功！");
		return result;
	}

	/**
	 * 提现失败给运营发送短信
	 * @param smsNo
	 * @param smsParams 要求字段顺序，数据库短信模板顺序：{0}快速提现出现问题，用户手机号：{1}，提现订单号：{2}错误信息：{3}，时间：{4}
	 * 【糯糯金融】"+productTitle+"快速提现出现问题，用户手机号："+userPhone+"，提现订单号："+orderId+" 错误信息："+errorMessage+"，时间："+sdf.format(new Date())
	 */
	@Async
	@Override
	public void sendErrorMessageForSystem(String smsNo, String... smsParams) {
	
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
		String content = "";
		String sendSmsChannel = "";
		try {
			ConfigSms ss = configSmsDao.selectByPrimaryKey(smsNo);
			String smsContext = ss.getSmsContext();
			Map<String, String> map = new HashMap<String, String>();
			int i = 0; 
			for (i = 0; i < smsParams.length; i++) {
				map.put(String.valueOf(i), smsParams[i]);
			}
			map.put(String.valueOf(i++), sdf.format(new Date()));
			content = "【糯糯金融】" + tSmsContent(smsContext, map);
			sendSmsChannel = ss.getSmsChannel();
			if (sendSmsChannel != null && "0".equals(sendSmsChannel.trim())) {
				// Channel=0 表示短信关闭
				logger.info("发送短信渠道：关闭");
			}

		} catch (Exception e) {
			logger.error("发送运营短信异常", e);
		}
		List<WithdrawErrorSendMobile> errorMobileList = userCardDao.selectSendErrorMobileList();
		for (WithdrawErrorSendMobile wes : errorMobileList) {
			Map<String, String> semParams = new HashMap<String, String>();
			// 查询短信渠道
			semParams.put("content", content);
			semParams.put("send_sms_channel", sendSmsChannel);
			semParams.put("mobileListParams", wes.getMobile());
			ZSHTPayThridPartyFunctionUtil.sendErrorMessage(semParams);
			
			// 保存验证码到DB
			try {
				this.saveSMS(wes.getMobile(), content, sendSmsChannel);
			} catch (Exception e) {
				logger.error("sendErrorMessageForSystem  短信保存失败，失败原因：" + e.getCause());
			}
		}

	}

	@Async
	@Override
	public void sendErrorMessageForUser(String smsNo, String userPhone, String bankAccountName) {
		String content = "";
		String sendSmsChannel = "";
		try {
			ConfigSms ss = configSmsDao.selectByPrimaryKey(smsNo);
			String smsContext = ss.getSmsContext();
			Map<String, String> map = new HashMap<String, String>();
			map.put("0", bankAccountName);

			content = "【糯糯金融】" + tSmsContent(smsContext, map);
			sendSmsChannel = ss.getSmsChannel();
			if (sendSmsChannel != null && "0".equals(sendSmsChannel.trim())) {
				// Channel=0 表示短信关闭
				logger.info("发送短信渠道：关闭");
			}
		} catch (Exception e) {
			logger.error("发送运营短信异常", e);
		}
		Map<String, String> semParams = new HashMap<String, String>();
		// 查询短信渠道
		semParams.put("content", content);
		semParams.put("send_sms_channel", sendSmsChannel);
		semParams.put("mobileListParams", userPhone);
		ZSHTPayThridPartyFunctionUtil.sendErrorMessage(semParams);
		// 保存验证码到DB
		try {
			this.saveSMS(userPhone, content, sendSmsChannel);
		} catch (Exception e) {
			logger.error("sendErrorMessageForUser  短信保存失败，失败原因：" + e.getCause());
		}
	}
	
	/**
	 * 发送个推消息
	 * 发送个推消息失败时，异常消息不用往外抛出，在异常捕获位置打印日志即可。
	 */
	public JSONObject sendGetuiMSG(Map<String,Object> reqmap){
		logger.info("#### 个推请求发送 开始 ####");
		try {
			String smsNo=reqmap.get("smsNo").toString();
			String[] smsParams=(String[])reqmap.get("smsParams");//消息模板里需要替换的变量
			ConfigSms ss = configSmsDao.selectByPrimaryKey(smsNo);//获取消息模板
			String smsContext = ss.getSmsContext();
			if(ss==null||StringUtils.isBlank(ss.getSmsContext())){
				 logger.error("/sendSMS/getSMS 短信不匹配!");
				 return null;
			}
			Map<String, String> map = new HashMap<String, String>();
			if ("sms01001".equals(smsNo)
					||"sms02001".equals(smsNo)
					||"sms05001".equals(smsNo)) {//加上用户姓名
				String mobile=reqmap.get("mobile").toString();
				Map<String,Object> reMap=(Map<String,Object>)configSmsDao.selectRealName(mobile);
				String readName=(String)reMap.get("REAL_NAME")==null?"":(String)reMap.get("REAL_NAME");
				if ("sms05001".equals(smsNo)) {
					smsParams[0]=readName;
				}else{
					smsParams[2]=readName;
				}
			}
			for(int i= 0;i < smsParams.length; i++) {
				 //修改所有涉及发短信金额保留两位小数
				if (i==0&&("sms01001".equals(smsNo) || "sms02001".equals(smsNo) || "sms03001".equals(smsNo)
						|| "sms04001".equals(smsNo) || "sms08001".equals(smsNo))) {
					map.put(String.valueOf(i),  CommonUtil.setFormatMoney(smsParams[i]));
				}else if(i==1&&("sms05001".equals(smsNo))){
					map.put(String.valueOf(i),  CommonUtil.setFormatMoney(smsParams[i]));
				}else{
					map.put(String.valueOf(i), smsParams[i]);
				}
			}
			String content = "【糯糯金融】" + tSmsContent(smsContext, map);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userId", reqmap.get("userId").toString());
			params.put("content", content);
			params.put("pushDetails", content);//消息详情，可在个人消息里看到
			params.put("title", reqmap.get("title").toString());
			params.put("messageDetailTypeNew", reqmap.get("messageDetailTypeNew"));//1.订制商品个人消息，2.充值或还款成功个人消息
			params.put("messageDetailResult", reqmap.get("messageDetailResult"));//0.执行成功消息提示，1.执行失败提示
			String path="/message/pushMessage";//请求
			
			logger.info("#### path=" + path + " ####");
			logger.info("#### 参数列表----> " + params.toString());
			String param = CommonUtil.getParam(params);
			try {
				param = DES3Util.encode(param);
			} catch (Exception e) {
				logger.error("个推请求发送，加密失败", e);
				return null;
			}
			// 调用shop接口
			String resultMsg = HttpRequestParam.sendGet(LoginRedirectUtil.interfacePathForShop + path, param);
			try {
				resultMsg = java.net.URLDecoder.decode(DES3Util.decode(resultMsg), "UTF-8");
			} catch (Exception e) {
				logger.error("个推请求发送，解密失败", e);
				e.printStackTrace();
			}
			logger.info("#### 请求结果---->" + resultMsg);
			logger.info("#### 个推请求发送 结束 ####");
			return JSONObject.fromObject(resultMsg);
		} catch (Exception e) {//发送个推消息失败时，异常消息不用往外抛出，在异常捕获位置打印日志即可。
			logger.error("发送个推消息失败！",e);
			logger.info("#### 个推请求发送 结束 ####");
			return null;
		}
	}
	
}
